package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddnewneedCompanyBinding;
import com.sgb.kjwl.model.entity.enterprise.NeedListItemEntity;
import com.sgb.kjwl.model.entity.enterprise.TaxscaleEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.pop.ChoiceMorePop;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.viewmodel.enterprise.AddNeed_ComPanyModel;
import com.swgk.core.customview.InputFilterUtils;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import java.util.ArrayList;
import java.util.List;

/**
 * 发布找公司
 */
public class AddNeed_CompanyActivity extends AppActivity {



    private AddNeed_ComPanyModel mModel;
    private ActivityAddnewneedCompanyBinding mBinding;
    private OptionsPickerView optionsPickerView_industry_type,optionsPickerView_enterprise_type;
    private CityPickView cityPickView;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Thread thread;
    private List<List<AddressEntity>> areaList;
    private Dialog choicemore = null;

    @Override
    protected void initView() {
        super.initView();
        mModel = new AddNeed_ComPanyModel(getApplication());
        mBinding =  DataBindingUtil.setContentView(this, R.layout.activity_addnewneed_company);
        mBinding.setVariable(BR.mComPanyModel,mModel);
        mBinding.setLifecycleOwner(this);

        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.tvName,15);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.tvinputtitle,50);
        mBinding.ediMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence editable, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                mBinding.ediMoney.removeTextChangedListener(this);

                if (s.contains(".")) {
                    mBinding.ediMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 3 + 1)});
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.substring(0,
                                s.indexOf(".") + 2 + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                } else {
                    mBinding.ediMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 1)});
                    if (s.length() > 10) {
                        s = s.substring(0, 10);
                        editable.replace(0, editable.length(), s.trim());
                    }
                }
                if (s.trim().equals(".")) {
                    s = "0" + s;
                    editable.replace(0, editable.length(), s.trim());
                }

                if (s.startsWith("0") && s.trim().length() > 1) {
                    if (!s.substring(1, 2).equals(".")) {
                        editable.replace(0, editable.length(), "0");
                    }
                }
                mBinding.ediMoney.addTextChangedListener(this);
            }
        });
        mModel.name.observe(this,String ->{
            if(String.indexOf(" ")>-1) {
                mModel.name.postValue(String.trim());
            }
        });
        mModel.contacts_name.observe(this,String ->{
            if(String.indexOf(" ")>-1) {
                mModel.contacts_name.postValue(String.trim());
            }
        });

        if(getIntent().getSerializableExtra("data")!=null){
            mModel.data=(NeedListItemEntity)getIntent().getSerializableExtra("data");
            mModel.setdata();

        }

        mModel.toast_message.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtil.show(AddNeed_CompanyActivity.this,s);
            }
        });

        mModel.showloading_diag.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                switch (integer){
                    case 1:
                        DialogHelper.showProgressDialog(AddNeed_CompanyActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                        break;
                    case 2:
                        DialogHelper.dismissProgressDialog();
                        break;

                    case 3://提交成功
                        DialogHelper.dismissProgressDialog();
//                        if(mModel.data!=null){
//                            Intent mintent = new Intent();
//                            mintent.putExtra("data",(Serializable)mModel.data);
//                            setResult(AddNeedDetailActivity.REQUEST_CODE,mintent);
//                        }
                        AddNeedListActivity.startactivity(AddNeed_CompanyActivity.this);
                        finish();
                        break;
                }
            }
        });
        mModel.is_bargaining.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mModel.money.postValue("");
                    mBinding.ediMoney.setEnabled(false);
                }else{
                    mBinding.ediMoney.setEnabled(true);
                }
            }
        });
        mModel.money.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(!TextUtils.isEmpty(s)){
                    mModel.is_bargaining.postValue(false);
                }
            }
        });

        mModel.showchoicepopwindow.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                KeyboardUtils.hideSoftInput(AddNeed_CompanyActivity.this);
                switch (integer){
                    case 1:
                        if(optionsPickerView_industry_type==null){
                            optionsPickerView_industry_type = new OptionsPickerBuilder(AddNeed_CompanyActivity.this, new OnOptionsSelectListener() {
                                @Override
                                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                    mModel.industry_type.postValue(mModel.industry_type_list.get(options1).name);
                                    mModel.industry_type_id = mModel.industry_type_list.get(options1).no;
                                }
                            }).setCancelText("取消").setSubCalSize(15)
                                    .setCancelColor(Color.parseColor("#666666"))
                                    .setTitleText("")
                                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                                    .setSubmitText("确定")
                                    .setSubmitColor(Color.parseColor("#5792FD"))
                                    .setTextColorCenter(Color.parseColor("#ff333333"))
                                    .setContentTextSize(15)
                                    .setLineSpacingMultiplier(2.5f)
                                    .setDividerColor(Color.parseColor("#EDEDED"))
                                    .setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
                            optionsPickerView_industry_type.setPicker(mModel.industry_type_list);
                            optionsPickerView_industry_type.setSelectOptions(0);
                        }
                        optionsPickerView_industry_type.show();
                        break;
                    case 2:
                        if(optionsPickerView_enterprise_type==null){
                            optionsPickerView_enterprise_type = new OptionsPickerBuilder(AddNeed_CompanyActivity.this, new OnOptionsSelectListener() {
                                @Override
                                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                    mModel.enterprise_type.postValue(mModel.enterprise_type_list.get(options1).name);
                                    mModel.enterprise_type_index = options1;
                                }
                            }).setCancelText("取消").setSubCalSize(15)
                                    .setCancelColor(Color.parseColor("#666666"))
                                    .setTitleText("选择类型")
                                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                                    .setSubmitText("确定")
                                    .setSubmitColor(Color.parseColor("#5792FD"))
                                    .setTextColorCenter(Color.parseColor("#ff333333"))
                                    .setContentTextSize(15)
                                    .setLineSpacingMultiplier(2.5f)
                                    .setDividerColor(Color.parseColor("#EDEDED"))
                                    .setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
                            optionsPickerView_enterprise_type.setPicker(mModel.enterprise_type_list);
                            optionsPickerView_enterprise_type.setSelectOptions(0);
                        }
                        optionsPickerView_enterprise_type.show();
                        break;


                    case 3://选择地址
                        if (isLoaded) {
                            showCityPop();
                        } else {
                            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
                        }
                        break;


                    case 4://选择纳税规模
                        if(choicemore==null){
                            choicemore = new ChoiceMorePop.Builder<TaxscaleEntity>(getActivity())
                                    .setListData(mModel.taxscale_list)
                                    .setTitle("")
                                    .setListOnclickLister(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            //点击确定
                                            String message = "";
                                            mModel.taxScale_data = "";
                                            for (TaxscaleEntity taxscaleEntity : mModel.taxscale_list) {

                                                if(taxscaleEntity.getChoice()){
                                                    message = message+taxscaleEntity.getText()+",";
                                                    if(taxscaleEntity.getText().equals("小规模")){
                                                       mModel.taxScale_data = mModel.taxScale_data+"0"+",";
                                                    }else   if(taxscaleEntity.getText().equals("一般纳税人")){
                                                        mModel.taxScale_data = mModel.taxScale_data+"1"+",";
                                                    }else   if(taxscaleEntity.getText().equals("出口纳税人")){
                                                        mModel.taxScale_data = mModel.taxScale_data+"2"+",";
                                                    }else   if(taxscaleEntity.getText().equals("未核税")){
                                                        mModel.taxScale_data = mModel.taxScale_data+"3"+",";
                                                    }
                                                }
                                            }
                                            if(!TextUtils.isEmpty(message)){
                                                message = message.substring(0,message.length()-1);
                                                mModel.taxscale.postValue(message);
                                            }
                                            if(!TextUtils.isEmpty( mModel.taxScale_data)){
                                                mModel.taxScale_data =  mModel.taxScale_data.substring(0, mModel.taxScale_data.length()-1);
                                            }

                                        }
                                    }).create();
                        }
                        choicemore.show();
                        break;
                }
            }
        });


    }



    private void showCityPop(){
        cityPickView = new CityPickBuilder(AddNeed_CompanyActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (mModel.opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = mModel.opt3.get(options1).get(options2).get(options3).getName();
                    //mAreaCode = opt3.get(options1).get(options2).get(options3).getNo();

                    mModel.cityPosition3 = options3;
                    //区
//                                    viewModel.storageManEntity.get().setDistrictName(areaName);
//                                    viewModel.storageManEntity.get().setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                    mModel.districtNo = mModel.opt3.get(options1).get(options2).get(options3).getNo();
                    mModel.areaName = mModel.opt3.get(options1).get(options2).get(options3).getName();
                }
                String content = mModel.datas.get(options1).getName() + "-" + mModel.opt2.get(options1).get(options2).getName() + "-" + areaName;
                mModel.regist_path.postValue(content);
                mModel.cityPosition1 = options1;
                mModel. cityPosition2 = options2;
                //省市
//                                viewModel.storageManEntity.get().setProvinceName(addressEntityList.get(options1).getName());
//                                viewModel.storageManEntity.get().setProvinceNo(addressEntityList.get(options1).getId());
                mModel.provinceNo = mModel.datas.get(options1).getId();
                mModel.provinceName = mModel.datas.get(options1).getName();
                //市
//                                viewModel.storageManEntity.get().setCityName(opt2.get(options1).get(options2).getName());
//                                viewModel.storageManEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
                mModel.cityNo = mModel.opt2.get(options1).get(options2).getNo();
                mModel.cityName = mModel.opt2.get(options1).get(options2).getName();

            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();
        cityPickView.setPicker(mModel.datas, mModel.opt2, mModel.opt3);
        cityPickView.setSelectOptions(mModel.cityPosition1, mModel.cityPosition2, mModel.cityPosition3);
        cityPickView.show();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {

        for (int i = 0; i < mModel.datas.size(); i++) {

            if (!TextUtils.isEmpty( mModel.provinceNo)) {
                if ( mModel.datas.get(i).getId().equals( mModel.provinceNo)) {
                    mModel.cityPosition1 = i;
                }
            }

//            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            mModel. opt2.add( mModel.datas.get(i).getChildren());
            for (int j = 0; j <  mModel.datas.get(i).getChildren().size(); j++) {

                if (!TextUtils.isEmpty( mModel.cityNo)) {
                    if ( mModel.datas.get(i).getChildren().get(j).getId().equals( mModel.cityNo)) {
                        mModel. cityPosition2 = j;
                    }
                }

                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children =  mModel.datas.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                    if (!TextUtils.isEmpty( mModel.districtNo)) {
                        for (int k = 0; k < children.size(); k++) {
                            if (children.get(k).getId().equals( mModel.districtNo)) {
                                mModel.cityPosition3 = k;
                            }
                        }
                    }
                }
                areaList.add(cityAreaList);
            }
            mModel. opt3.add(areaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }


    public static void startactivity(Context mContext){
        Intent mIntent = new Intent();
        mIntent.setClass(mContext,AddNeed_CompanyActivity.class);
        mContext.startActivity(mIntent);
    }
}
